package com.gateway.common;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

/**
 * @author xiangminwen
 * @date 2025/2/20 15:48
 */
public class JacksonUtil {

    private static final Logger LOG = LoggerFactory.getLogger(JacksonUtil.class);
    public static final ObjectMapper MAPPER = new ObjectMapper();

    public JacksonUtil() {
    }

    public static String toJson(Object obj) {
        try {
            return MAPPER.writeValueAsString(obj);
        } catch (Exception var2) {
            Exception e = var2;
            LOG.error("toJson error", e);
            throw new RuntimeException(e);
        }
    }

    public static <T> List toList(String json, Class<T> clazz) {
        try {
            if (StringUtils.isEmpty(json)) {
                return null;
            } else {
                JavaType javaType = getCollectionType(ArrayList.class, clazz);
                return MAPPER.readValue(json, javaType);
            }
        } catch (Exception var3) {
            Exception e = var3;
            LOG.error("toList error", e);
            throw new RuntimeException(e);
        }
    }

    public static <T> Map toMap(String json, Class<T> clazz) {
        try {
            if (StringUtils.isEmpty(json)) {
                return null;
            } else {
                JavaType javaType = getCollectionType(HashMap.class, String.class, clazz);
                return MAPPER.readValue(json, javaType);
            }
        } catch (Exception var3) {
            Exception e = var3;
            LOG.error("toMap error", e);
            throw new RuntimeException(e);
        }
    }

    public static <T> T fromObj(String json, Class<T> clazz) {
        try {
            return StringUtils.isEmpty(json) ? null : MAPPER.readValue(json, clazz);
        } catch (Exception var3) {
            Exception e = var3;
            LOG.error("fromObj error", e);
            throw new RuntimeException(e);
        }
    }

    private static JavaType getCollectionType(Class<?> parametrized, Class<?>... parameterClass) {
        return MAPPER.getTypeFactory().constructParametricType(parametrized, parameterClass);
    }

    static {
        MAPPER.setSerializationInclusion(Include.NON_NULL);
        MAPPER.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
}
